from functools import wraps
from src.db import dbs, dbm
from sqlalchemy.orm import scoped_session
from src.core.variables.constant import *


class safe_kit:
    @classmethod
    def all_apps(cls, func):
        @wraps(func)
        def wapper(*args, **kwargs):
            # 将绝对路径中的部分使用名称替换，隐藏真实路径
            result = {}
            func_result, user = func(*args, **kwargs)
            for index_i, value_i in func_result.items():
                temp = {}
                for index, value in value_i.items():
                    path_replacements = {
                        CONF.PATH.REPO: CONF.PATH.STR.REPO,
                        CONF.PATH.LOG: CONF.PATH.STR.LOG,
                        CONF.PATH.TEMP: CONF.PATH.STR.TEMP,
                        CONF.PATH.RUN_JAVA: CONF.PATH.STR.RUN,
                        CONF.PATH.RUN_STATIC: CONF.PATH.STR.RUN,
                    }
                    for k in path_replacements.keys():
                        if k in path_replacements:
                            value = value.replace(k, path_replacements[k])
                    temp[index] = value
                result[index_i] = temp
            return result, user

        return wapper

    @classmethod
    def mn_node_translate(cls, func):
        @wraps(func)
        def wapper(*args, **kwargs):
            result = {}
            func_result, user = func(*args, **kwargs)
            if user.username == 'multi_nodes':
                for index_i, value_i in func_result.items():
                    with dbm.get(f'sys_default') as db_session:
                        db_session: scoped_session
                        node_id = db_session.query(dbs.sys_default.Node).filter(dbs.sys_default.Node.host == "localhost").first().node_id
                        value_i['node'] = node_id
                    result[index_i] = value_i
                return result
            return func_result

        return wapper